package com.pay.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.utils.OutChannel;
import com.pay.utils.PayConfig;
import com.pay.utils.RSAUtil;
import com.pay.utils.RequestUtils;

@RestController
public class PayController {


    @RequestMapping("/pay")
    ModelAndView login() {
        return  new ModelAndView("/pay");
    }
    
    @RequestMapping("/create/order")
    ModelAndView payQrcode(String amount,String outChannel) {
        return  new ModelAndView("/payQrcode");
    }
    
    /**
     * 支付宝，微信扫码支付demo
     * 返回参数： 二维码生成
     * */
    public String qrcodePay(String amount,String outChannel) throws Exception{
		// TODO Auto-generated method stub
		JSONObject jsObj = new JSONObject();
		String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		//商户号
		jsObj.put("merchNo", PayConfig.merchNo);
		//订单号
		jsObj.put("orderNo", reqTime + new Random().nextInt(10000));	
		//支付渠道
		jsObj.put("outChannel", OutChannel.wxpayqrcode.name());
		//订单标题 
		jsObj.put("title", "商城网银下单");
		//产品名称
		jsObj.put("product", "产品名称");
		//支付金额 单位 元 
		jsObj.put("amount", String.valueOf(new Random().nextInt(5000)));
		//币种
		jsObj.put("currency", "CNY");
		//前端返回地址
		jsObj.put("returnUrl", "http://www.baidu.com");
		//后台通知地址
		jsObj.put("notifyUrl", "http://www.baidu.com");
		//请求时间
		jsObj.put("reqTime", reqTime);
		//userId
		jsObj.put("userId", "oTZZ0wLl6FJkgX42zM8F_dUjv-bk");
		//对公
		jsObj.put("acctType", 1);
		System.out.println("请求source:" + jsObj.toString());
		byte[] context = RSAUtil.encryptByPublicKey(JSON.toJSONBytes(jsObj), PayConfig.publicKey);
		String sign = RSAUtil.sign(context, PayConfig.mcPrivateKey);
		System.out.println("签名结果：" + sign);
		JSONObject jo = new JSONObject();
		jo.put("sign", sign);
		jo.put("context", context);
		System.out.println("请求参数："+ jo.toJSONString());
		String result = RequestUtils.doPostJson(PayConfig.url, jo.toJSONString());
		System.out.println("请求结果！"+result);
		jo = JSONObject.parseObject(result);
		if("0".equals(jo.getString("code"))){
			sign = jo.getString("sign");
			context = jo.getBytes("context");
			if(RSAUtil.verify(context, PayConfig.publicKey, sign)){
				String source = new String(RSAUtil.decryptByPrivateKey(context, PayConfig.mcPrivateKey));
				System.out.println("解密结果：" + source);
				jo = JSONObject.parseObject(source);
				String qrcode_url = jo.getString("qrcode_url");
				return qrcode_url;
				
			}else{
				System.out.println("验签失败！{}");
			}
		}
		return null;
    }
    


   
}
